package com.lyz.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyz.models.User;
import com.lyz.models.UserVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.Objects;

public class TokenUtil {
    /**
     * 私钥
     */
    private static final String SECRET = "lyzSecret";

    /**
     * 过期时间
     */
    private static final long TTL = (24 * 60 * 60);

    public static final String TOKEN_HEADER = "Authorization";

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String create(Object obj) {
        try {
            String subject = MAPPER.writeValueAsString(obj);
            Date now = new Date();
            Date expiredDate = new Date(now.getTime() + TTL * 1000);
            JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                    .setSubject(subject)
                    .setIssuedAt(now)
                    .setExpiration(expiredDate)
                    .signWith(SignatureAlgorithm.HS512, SECRET);
            return builder.compact();
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parse(String token, Class<T> cls) {
        Claims body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        if (Objects.isNull(body)) {
            throw new RuntimeException("UnAuthorization");
        }
        String subject = body.getSubject();
        if (Objects.isNull(subject)) {
            throw new RuntimeException("UnAuthorization");
        }
        try {
            return MAPPER.readValue(subject, cls);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("UnAuthorization");
        }
    }

    public static boolean expired(String token) {
        Claims body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        if (Objects.isNull(body)) {
            throw new RuntimeException("UnAuthorization");
        }
        Date expiration = body.getExpiration();
        return expiration.before(new Date());
    }

    public static void main(String[] args) {
        User user = new User()
                .setId(2)
                .setAccount("456789")
                .setPassword("123456")
                .setName("李四")
                .setPermission("admin");
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        System.out.println(TokenUtil.create(userVO));
    }

}
